# encoding: utf-8
# 项目名称： day02
# @File  : order.py
# @Author: sun hao
# @Desc : 订单管理
# @Date  :   16:41 2024/10/20

import json
import random
import time
from datetime import datetime
from django import forms
from django.contrib.admin.templatetags.admin_list import result_list
from django.shortcuts import HttpResponse, render, redirect
from django.http import JsonResponse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.views.decorators.csrf import csrf_exempt
from app01.utils.layUI import LayUiModelForm
from app01 import models


def generate_order_number(user_id):
    # 获取当前时间的毫秒级时间戳
    timestamp = int(time.time() * 1000)
    # 生成一个六位的随机数
    random_part = random.randint(100000, 999999)
    # 结合用户的唯一标识符
    order_number = f'ZJ{timestamp}{user_id}{random_part}'
    return order_number


class OrderModelForm(LayUiModelForm):
    class Meta:
        model = models.Order
        fields = '__all__'  # 展示全部字段
        exclude = ['oid', 'user']  # 排除 oid 订单号字段不显示,当前提交者 user 不显示

    # 添加字段验证
    def clean(self):
        cleaned_data = super().clean()
        # 检查特定字段是否为空
        if not cleaned_data.get('title'):
            self.add_error('title', '标题不能为空')
        if not cleaned_data.get('price'):
            self.add_error('price', '价格不能为空')
        # 可以根据需要添加更多字段的验证


def order_list(request):
    # 获取并验证分页参数
    form = OrderModelForm()
    try:
        page = max(1, int(request.GET.get('page', 1)))
    except ValueError:
        page = 1

    try:
        limit = max(1, min(100, int(request.GET.get('limit', 10))))
    except ValueError:
        limit = 10

    # 查询数据并排序
    queryset = models.Order.objects.all().order_by('-id')

    # 使用Django的Paginator进行分页
    paginator = Paginator(queryset, limit)
    try:
        data_list = paginator.page(page)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)

    context = {
        'form': form,
        'data_list': data_list,
        'totals': paginator.count,
        'current_page': data_list.number,
        'page_size': limit,
        'total_pages': paginator.num_pages,
    }

    return render(request, 'order/list.html', context)


@csrf_exempt
def order_add(request):
    """
        新建订单,前端通过ajax来交互数据
    """
    print(request.GET)
    print(request.POST)
    form = OrderModelForm(request.POST)
    if form.is_valid():
        # 订单号生成
        # form.instance.oid = "xxxxxxxx-xxxx-xxxx"
        print(request.session["login_info"]['id'])
        form.instance.oid = generate_order_number(request.session["login_info"]['id'])  # 生成订单号
        form.instance.user_id = request.session["login_info"]['id']  # 当前的登陆者
        # 验证成功
        form.save()
        data_dict = {"status": True, "code": "200"}
        return JsonResponse(data_dict)
    # form.errors
    data_dict = {"status": False, "code": "500", "error": form.errors}
    return JsonResponse(data_dict)


def order_details(request):
    """
        获取对应订单的具体信息,通过id
    """
    order_id = request.GET.get('order_id')
    row_dict = models.Order.objects.filter(id=order_id).values("oid", "title", "price",
                                                               "status").first()  # 返回一个对象,当前行的所有数据
    print(row_dict)  # {'title': '通义千问', 'price': Decimal('4789.00'), 'status': 2}
    if not row_dict:
        data_dict = {"status": False, "code": "500", "message": "该订单记录不存在,无法查询数据"}
        return JsonResponse(data_dict)

    # 方式1 S
    # 获取到对象，没法序列化返回给浏览器,不能直接给 row_obj
    # data_dict = {"status": True, "code": "200", "data": {
    #     "title": row_obj.title,
    #     "price": row_obj.price,
    #     "status": row_obj.status,
    # }}
    # return JsonResponse(data_dict)
    # 方式1 E

    # 方式2 S
    data_dict = {"status": True, "code": "200", "data": row_dict}
    return JsonResponse(data_dict)
    # 方式2 E


@csrf_exempt
def order_edit(request):
    """
        编辑订单
    """
    order_id = request.GET.get('order_id')
    row_dict = models.Order.objects.filter(id=order_id).first()  # 返回一个对象,当前行的所有数据
    if not row_dict:
        data_dict = {"status": False, "code": "500", "message": "该订单记录不存在,无法更新数据"}
        return JsonResponse(data_dict)

    form = OrderModelForm(data=request.POST, instance=row_dict)
    if form.is_valid():
        form.save()
        data_dict = {"status": True, "code": "200", "message": "订单已经更新"}
        return JsonResponse(data_dict)

    data_dict = {"status": False, "code": "500", "message": "数据更新异常，请查看日志", "error": form.errors}
    return JsonResponse(data_dict)


@csrf_exempt
def order_delete(request):
    """
        删除订单
    """
    order_id = request.GET.get('order_id')
    isExists = models.Order.objects.filter(id=order_id).exists()
    if not isExists:
        data_dict = {"status": False, "code": "500", "message": "该id记录不存在"}
        return JsonResponse(data_dict)
    models.Order.objects.filter(id=order_id).delete()
    data_dict = {"status": True, "code": "200", "message": "该记录已删除"}
    return JsonResponse(data_dict)
